package com.uchengwang.ui.cm_ui.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.LoginConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.cycle.bean.BottomBean;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.login.bean.WXUserInfoBean;
import com.uchengwang.ui.cm_ui.me.presenter.HttpUserManager;
import com.uchengwang.ui.utils.ActivityUtils;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.ImageManagerUtils;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.MD5;
import com.uchengwang.ui.utils.PopupUtils;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.UCommonUtil;
import com.uchengwang.ui.view.CircleImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by U城网 on 2018/2/5.
 * 注册 完善资料页
 */

public class CompleteInfoActivity extends AllBaseActivity implements View.OnClickListener{
    private ActivityTitleBar bar;
    private CircleImageView head;
    private RelativeLayout sex_rl, nickName_rl, school_rl;
    private Button ok;
    private TextView sex, nickName, school;

    private String nickNameString;
    private List<BottomBean> beanList;
    private String headUrl;

    private WXUserInfoBean userBean;//三方登录时 使用三方提供的用户信息
    private String ossSuccessHead, schoolName;
    private int chooseSex =-1;
    private long uniId;

    private String phoneS, codeS, passwordS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_complete_info);
        userBean = (WXUserInfoBean) getIntent().getSerializableExtra(BaseConfig.BEAN);

        phoneS = getIntent().getStringExtra(BaseConfig.MOBILE);
        codeS = getIntent().getStringExtra(BaseConfig.CODE);
        passwordS = getIntent().getStringExtra(BaseConfig.PASS_WORD);

        initView();
    }

    private void initView(){
        bar = (ActivityTitleBar) findViewById(R.id.data_bar);
        head = (CircleImageView) findViewById(R.id.data_head);
        head.setOnClickListener(this);
        sex_rl = (RelativeLayout) findViewById(R.id.data_sex_rl);
        sex_rl.setOnClickListener(this);
        nickName_rl = (RelativeLayout) findViewById(R.id.data_nickName_rl);
        nickName_rl.setOnClickListener(this);
        school_rl = (RelativeLayout) findViewById(R.id.data_school_rl);
        school_rl.setOnClickListener(this);
        ok = (Button) findViewById(R.id.data_ok);
        ok.setOnClickListener(this);
        sex = (TextView) findViewById(R.id.data_sex);
        nickName = (TextView) findViewById(R.id.data_nickName);
        school = (TextView) findViewById(R.id.data_school);

        bar.setTitle("完善资料", 0);
        bar.setLeftVisible(false);

        initViewData();
    }

    /**
     * 三方登录获取的用户信息
     * */
    private void initViewData(){
        if (userBean != null){
            ossSuccessHead = userBean.getHeadimgurl();
            ImageManager.getInstance().loadImage(this, head, ossSuccessHead, ImageManager.ImageType.CIRCLE);

            nickNameString = userBean.getNickname();
            nickName.setText(nickNameString);

            chooseSex = userBean.getSex();
            sex.setText(chooseSex ==1? "男" : "女");

            bingOtherLogin();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.data_head://点击头像
                chooseImage();
                break;
            case R.id.data_sex_rl://选择性别
                if (beanList ==null){
                    beanList = new ArrayList<>();
                    beanList.add(new BottomBean(true, "性别选择后不可更改哦", 0, R.color.comment_color, R.drawable.shape_top_left_right_white));
                    beanList.add(new BottomBean(true, "男", R.drawable.icon_man, R.color.login_bt_color, R.drawable.selector_linear_bg));
                    beanList.add(new BottomBean(true, "女", R.drawable.icon_woman, R.color.ucw_color, R.drawable.selector_bottom));
                }
                PopupUtils.getUtils().bottom(this, beanList, false, bar, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        PopupUtils.getUtils().dismiss();
                        switch (position){
                            case 0://标题
                                break;
                            case 1://男
                            case 2://女
                                String c = beanList.get(position).getName();
                                chooseSex = (c.equals("男") ? 1 : 0);
                                sex.setText(beanList.get(position).getName());
                                break;
                        }
                    }
                });

                break;
            case R.id.data_nickName_rl://填写昵称
                View view = LayoutInflater.from(this).inflate(R.layout.layout_complete_data, null, false);
                TextView data_title = (TextView) view.findViewById(R.id.data_title);
                data_title.setText("昵称");

                final TextView data_num = view.findViewById(R.id.data_num);
                data_num.setText("0/"+15);

                final EditText editText = view.findViewById(R.id.data_group);

                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        data_num.setText(s.length() +"/" + 15);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });

                if (!TextUtils.isEmpty(nickNameString)){
                    nickNameString = nickNameString.trim();
                    editText.setText(nickNameString);
                }


                Button cancel = view.findViewById(R.id.data_cancel);
                Button data_sure = view.findViewById(R.id.data_sure);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtils.getUtils().cancel();
                    }
                });
                data_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        nickNameString = editText.getText().toString();
                        nickNameString = nickNameString.trim();
                        if (TextUtils.isEmpty(nickNameString)){
                            UCommonUtil.getUtil().showToast(CompleteInfoActivity.this, "请输入昵称");
                            return;
                        }
                        nickName.setText(nickNameString);
                        DialogUtils.getUtils().cancel();
                    }
                });
                DialogUtils.getUtils().initView(this, view, true, null);

                break;
            case R.id.data_school_rl://选择学校
                Intent intent = new Intent(this, SelectSchoolActivity.class);
                intent.putExtra(BaseConfig.TYPE, 1);
                startActivityForResult(intent, 1);
                break;

            case R.id.data_ok://确定
                if (TextUtils.isEmpty(headUrl) && TextUtils.isEmpty(ossSuccessHead)){
                    UCommonUtil.getUtil().showToast(this, "请选择头像");
                    return;
                }

                if (chooseSex <0){
                    UCommonUtil.getUtil().showToast(this, "请选择性别");
                    return;
                }


                if (TextUtils.isEmpty(nickNameString)){
                    UCommonUtil.getUtil().showToast(this, "请输入昵称");
                    return;
                }

//                if (TextUtils.isEmpty(schoolName)){
//                    UCommonUtil.getUtil().showToast(this, "请选择学校");
//                    return;
//                }
                if (!TextUtils.isEmpty(ossSuccessHead)){
                    //头像被传上oss
                    reg();
                }else {
                    postHead();
                }

                break;
        }
    }

    /**
     * 选择图片
     * */
    private void chooseImage(){
        UCommonUtil.getUtil().openAndCrop(this, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                Log.d("jjf", "裁剪的地址="+data);
                headUrl = data;
                if (!TextUtils.isEmpty(headUrl)){
                    ImageManager.getInstance().loadImage(CompleteInfoActivity.this, head, new File(headUrl), ImageManager.ImageType.CIRCLE);
                }
            }
        });
    }

    /**
     * 点击下一步
     * */
    private void postHead(){
        LoadingUtils.getUtils().loading(this);
        ImageManagerUtils.getUtils().compressAndPost(this, headUrl, 500, new ImageManagerUtils.ImageCompressListener() {
            @Override
            public void onResult(int stutas, String cover, String result) {
                if (stutas ==0){
                    //上传oss成功
                    ossSuccessHead = result;
                    reg();
                }else {
                    LoadingUtils.getUtils().hide();
                    UCommonUtil.getUtil().showToast(CompleteInfoActivity.this, result);
                }
            }
        });
    }


    /**
     * 注册
     * */
    private void reg(){
        if (TextUtils.isEmpty(passwordS)){
            UCommonUtil.getUtil().showToast(this, "请设置密码");
            return;
        }

        LoadingUtils.getUtils().loading(this);
        MapRequest map = new MapRequest();
        map.put(BaseConfig.USER_NAME, phoneS);
        map.put(BaseConfig.MOBILE, phoneS);
        map.put(BaseConfig.USER_PWD, MD5.md5(String.valueOf(passwordS)));
        map.put(BaseConfig.OPT_SYSTEM, BaseConfig.system);
        map.put(BaseConfig.DEVICE_ID, UCommonUtil.getUtil().getDeviceId(this));
        map.put(BaseConfig.VALID_CODE, codeS);

        map.put(BaseConfig.USER_AVATAR, ossSuccessHead);
        map.put(BaseConfig.SEX, chooseSex);
        map.put(BaseConfig.NICK_NAME, nickNameString);
        map.put(BaseConfig.UNI_ID, uniId);
        map.put(BaseConfig.UNI_NAME, schoolName);
        HttpManager.newInstance(this).query(LoginConfig.Register.method, LoginConfig.Register.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(CompleteInfoActivity.this, msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                LoadingUtils.getUtils().hide();
                if (status == 0){
                    //注册成功
                    ActivityUtils.getUtils().clearMainActivity();

                    UserBean userBean = JsonUtils.getManager().stringToBean(data, UserBean.class);
                    UChengApplication.TOKEN = userBean.getToken();
                    UChengApplication.uid = userBean.getId();
                    UChengApplication.nickName = userBean.getNickName();
                    UChengApplication.uniId = userBean.getUniId();
                    UChengApplication.myUniId =userBean.getUniId();
                    UChengApplication.userRole = userBean.getUserRole();

                    UChengApplication.schoolName = userBean.getUniName();
                    UChengApplication.mySchoolName = userBean.getUniName();

                    UChengApplication.nickName = nickNameString;
                    UChengApplication.uniId = uniId;
                    UChengApplication.myUniId = uniId;
                    UChengApplication.schoolName = schoolName;
                    UChengApplication.mySchoolName = schoolName;
                    UChengApplication.userAvatar = ossSuccessHead;
                    UChengApplication.sex = chooseSex;

                    LiteOrmDBUtil.getLiteOrm(CompleteInfoActivity.this);

                    SPUtils.getPreferences(CompleteInfoActivity.this).setAccountId(userBean.getId());
                    SPUtils.getPreferences(CompleteInfoActivity.this).setAccountPw(MD5.md5(String.valueOf(passwordS)));
                    SPUtils.getPreferences(CompleteInfoActivity.this).setUserName(phoneS);
                    SPUtils.getPreferences(CompleteInfoActivity.this).setRealName(userBean.getRealName());
                    SPUtils.getPreferences(CompleteInfoActivity.this).setToken(userBean.getToken());
                    SPUtils.getPreferences(CompleteInfoActivity.this).setTokenTime();
                    SPUtils.getPreferences(CompleteInfoActivity.this).setLinkMainToken(userBean.getToken());
                    SPUtils.getPreferences(CompleteInfoActivity.this).putInt(BaseConfig.USER_ROLE, userBean.getUserRole());


                    SPUtils.getPreferences(CompleteInfoActivity.this).putInt(BaseConfig.SEX, chooseSex);
                    SPUtils.getPreferences(CompleteInfoActivity.this).putString(BaseConfig.NICK_NAME, nickNameString);
                    SPUtils.getPreferences(CompleteInfoActivity.this).putString(BaseConfig.USER_AVATAR, ossSuccessHead);
                    SPUtils.getPreferences(CompleteInfoActivity.this).putLong(BaseConfig.UNI_ID, uniId);
                    SPUtils.getPreferences(CompleteInfoActivity.this).putString(BaseConfig.UNI_NAME, schoolName);

                    startActivity(new Intent(CompleteInfoActivity.this, MainActivity.class));
                }else {
                    UCommonUtil.getUtil().showToast(CompleteInfoActivity.this, msg);
                }
            }
        });
    }

    /**
     * 提交信息
     * */
//    private void submitInfo(){
//        MapRequest map = new MapRequest();
//        map.put(BaseConfig.USER_AVATAR, ossSuccessHead);
//        map.put(BaseConfig.SEX, chooseSex);
//        map.put(BaseConfig.NICK_NAME, nickNameString);
//        map.put(BaseConfig.UNI_ID, uniId);
//        map.put(BaseConfig.UNI_NAME, schoolName);
//        HttpUserManager.getManager().changeUserInfo(this, map, new OnResultListener() {
//            @Override
//            public void onResult(int stutas, String msg, int total, String data) {
//                if (stutas ==0){
//                    UChengApplication.nickName = nickNameString;
//                    UChengApplication.uniId = uniId;
//                    UChengApplication.myUniId = uniId;
//                    UChengApplication.schoolName = schoolName;
//                    UChengApplication.mySchoolName = schoolName;
//                    UChengApplication.userAvatar = ossSuccessHead;
//                    UChengApplication.sex = chooseSex;
//
//                    SPUtils.getPreferences(CompleteInfoActivity.this).putInt(BaseConfig.SEX, chooseSex);
//                    SPUtils.getPreferences(CompleteInfoActivity.this).putString(BaseConfig.NICK_NAME, nickNameString);
//                    SPUtils.getPreferences(CompleteInfoActivity.this).putString(BaseConfig.USER_AVATAR, ossSuccessHead);
//                    SPUtils.getPreferences(CompleteInfoActivity.this).putLong(BaseConfig.UNI_ID, uniId);
//                    SPUtils.getPreferences(CompleteInfoActivity.this).putString(BaseConfig.UNI_NAME, schoolName);
//
////                    startActivity(new Intent(CompleteInfoActivity.this, ChooseCycleActivity.class));
//                    startActivity(new Intent(CompleteInfoActivity.this, MainActivity.class));
//                }else {
//                    UCommonUtil.getUtil().showToast(CompleteInfoActivity.this, msg);
//                }
//            }
//        });
//    }

    /**
     * 三方注册成功 将微信的unionId绑定自己的id
     * oauthType 0=WX 1=WB 2=QQ
     * */
    public void bingOtherLogin(){
        MapRequest map = new MapRequest();
        switch (userBean.getOauthType()){
            case 0:
                map.put(BaseConfig.OAUTH_TYPE, "WX");
                break;
            case 1:
                map.put(BaseConfig.OAUTH_TYPE, "WB");
                break;
            case 2:
                map.put(BaseConfig.OAUTH_TYPE, "QQ");
                break;
        }
        map.put(BaseConfig.OAUTH_CODE, userBean.getUnionid());
        HttpUserManager.getManager().changeUserInfo(this, map, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                Log.d("jjf", "绑定是否成功=="+stutas);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode ==1 && data != null){
            uniId = data.getLongExtra(BaseConfig.UNI_ID, 0);
            schoolName = data.getStringExtra(BaseConfig.UNI_NAME);
            school.setText(schoolName);
        }
    }
}
